<?php

class RegistrationOption extends DataExtension implements PermissionProvider {
	private static $db = array(
		'AllowRegisterFree' => 'Boolean',
		'AllowRegisterWithoutPayment' => 'Boolean',
		'AllowUpgradeFree' => 'Boolean',
		'AllowUpgradeWithoutPayment' => 'Boolean',
		'RegisterType' => 'Varchar'
	);
	
	private static $defaults = array('RegisterType' => 'Backend');
	
	function updateFieldLabels(&$labels) {
        $labels['AllowRegisterFree'] = _t('RegistrationOption.ALLOW_REGISTER_FREE', 'Allow register for free');
		$labels['AllowRegisterWithoutPayment'] = _t('RegistrationOption.ALLOW_REGISTER_WITHOUT_PAYMENT', 'Allow register without payment');
		$labels['AllowUpgradeFree'] = _t('RegistrationOption.ALLOW_UPGRADE_FREE', 'Allow upgrade for free');
		$labels['AllowUpgradeWithoutPayment'] = _t('RegistrationOption.ALLOW_UPGRADE_WITHOUT_PAYMENT', 'Allow upgrade without payment');
		$labels['RegisterType'] = _t('RegistrationOption.REGISTER_TYPE', 'Register Type');
	}
	
	function updateCMSFields(FieldList $fields) {
		if(!Permission::check('ALLOW_RegistrationOption')){
			$fields->removeByName('AllowRegisterFree');
        	$fields->removeByName('AllowRegisterWithoutPayment');
		}

		if(!Permission::check('ALLOW_UpgradeOption')){
			$fields->removeByName('AllowUpgradeFree');
        	$fields->removeByName('AllowUpgradeWithoutPayment');
		}
		
		$fields->removeByName('RegisterType');
    }

	function updateFrontendFields(FieldList $fields) {
		$fields->removeByName('AllowRegisterFree');
        $fields->removeByName('AllowRegisterWithoutPayment');
		$fields->removeByName('AllowUpgradeFree');
        $fields->removeByName('AllowUpgradeWithoutPayment');
		$fields->removeByName('RegisterType');
    }

	function updateMemberFormFields(FieldList $fields) {
        $fields->removeByName('AllowRegisterFree');
        $fields->removeByName('AllowRegisterWithoutPayment');
		$fields->removeByName('AllowUpgradeFree');
        $fields->removeByName('AllowUpgradeWithoutPayment');
		$fields->removeByName('RegisterType');
    }
	
	function onBeforeWrite(){
		if($this->owner->RegisterType == 'WithoutPayment'){
			$this->owner->NoUnilevelPayout = 1;
			$this->owner->NoPairingPayout = 1;
			$this->owner->NoMatchingPayout = 1;
			$this->owner->NoInvestPayout = 1;
		}
	}
	
	public function providePermissions() {
        return array(
            'ALLOW_RegistrationOption' => array(
                'name' => _t('RegistrationOption.PERMISSION_ALLOW_REGISTRATION_OPTION', 'Allow edit registration option'),
                'category' => ''
            ),
            'ALLOW_UpgradeOption' => array(
                'name' => _t('RegistrationOption.PERMISSION_ALLOW_UPGRADE_OPTION', 'Allow edit upgrade option'),
                'category' => ''
            )
        );
    }
}
